package com.hankol.winecellar


import android.app.AlertDialog
import android.os.Bundle
import android.os.CountDownTimer
import android.text.TextUtils
import android.view.View
import android.widget.TextView
import com.alibaba.android.arouter.facade.annotation.Route
import com.baselibrary.Constants
import com.baselibrary.MessageBus
import com.baselibrary.activity.BaseActivity
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.checkValue
import com.baselibrary.extension.load
import com.baselibrary.extension.toast
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.hankol.winecellar.bean.PrivateMealManageListBean
import com.hankol.winecellar.bean.WineryCoverBean
import com.hankol.winecellar.databinding.ActivityPublishPrivateMealBinding
import com.hankol.winecellar.utils.EditInputUtils
import com.media.utils.WineryAboutUtils
import com.hankol.winecellar.view.MyCircleProgress
import com.hankol.winecellar.viewmodel.WineCellarViewModel
import com.media.publish.bean.MultiImageResp
import com.media.publish.utils.UploadMediaUtils
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**发布下酒菜
 * @author: merbng
 * @description:
 */
@Route(path = ActivityRouter.WINE_CELLAR.PUBLISH_PRIVATE_MEAL)
class PublishPrivateMealActivity : BaseActivity(), View.OnClickListener {

    private lateinit var viewModel: WineCellarViewModel
    private lateinit var binding: ActivityPublishPrivateMealBinding

    var dataBean: PrivateMealManageListBean? = null

    override fun getLayoutId(): Int {
        return R.layout.activity_publish_private_meal
    }

    override fun init() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        binding = getDataBinding()
        viewModel = getActivityViewModelProvider(this).get(WineCellarViewModel::class.java)
        binding.ivBack.setOnClickListener { finish() }
        if (bundle.checkNotNull()) {
            dataBean =
                bundle?.getParcelable<PrivateMealManageListBean>(Constants.KEY_PRIVATE_MEAL_BEAN)
        }
        initView()
        initListener()
        initObserver()
        //回显数据
        initData()
    }

    private lateinit var countDownTimer: CountDownTimer
    var uploadLoadingDialog: AlertDialog? = null
    fun showLoading() {
        uploadLoadingDialog =
            com.hankol.winecellar.utils.PopUtils.uploadLoadingDialog(this, object : com.hankol.winecellar.utils.PopUtils.ICallback4Progress {
                override fun progressCallback(progress: MyCircleProgress, tvProgress: TextView) {
                    countDownTimer = object : CountDownTimer(60000, 3000) {
                        override fun onTick(millisUntilFinished: Long) {
                            val pro = (60000 - millisUntilFinished) / 1000
                            progress.setMax(60)
                            progress.setCurrent(pro.toInt())
                        }

                        override fun onFinish() {}
                    }.start()
                }
            })
        if (!uploadLoadingDialog!!.isShowing) {
            uploadLoadingDialog!!.show()
        }
    }

    fun hideLoading() {
        countDownTimer.cancel()
        if (uploadLoadingDialog.checkNotNull()) {
            uploadLoadingDialog!!.dismiss()
        }
    }

    private fun initObserver() {
        viewModel.publishMealLD.observe(this, androidx.lifecycle.Observer {
            hideLoading()
            if (it) {
                //通知删除临时图片
                EventBusUtils.sendNotify(MessageBus.msgid_img_upload_succ_need_delete_temp)
                SensorsDataManager.instance.operatorCreateFood(SpUtils.getInstance().currentWineryInfo.wineryName.checkValue())
                "发布成功".toast()
                finish()
            }
        })
    }

    //回显数据
    private fun initData() {
        dataBean?.let {
            binding.ivDel.visibility = View.VISIBLE
            //图片剪裁回调，主线程
            //注意：剪裁回调里的ImageItem中getCropUrl()才是剪裁过后的图片地址
            wineryCoverBean = CommonUtil.jsonToBean(it.appetizerImg, WineryCoverBean::class.java)
            viewModel.privateMealImgPath.value =
                if (wineryCoverBean.type == 0) wineryCoverBean.coverUrl.checkValue() else wineryCoverBean.videoUrl.checkValue()
            binding.imgVideoTag.visibility =
                if (wineryCoverBean.type == 1) View.VISIBLE else View.GONE
            binding.ivFragmentAgencyImage.load(
                ContextUtils.getCurApplication().applicationContext,
                viewModel.privateMealImgPath.value.checkValue()
            )
            binding.etName.setText("${it.appetizerName.checkValue()}")
            binding.etDesc.setText("${it.appetizerDesc.checkValue()}")
            binding.etSort.setText("${it.sort}")
        }
    }

    private fun initListener() {
        binding.ivFragmentAgencyImage.setOnClickListener(this)
        binding.ivDel.setOnClickListener(this)
        binding.tvEnter.setOnClickListener(this)
    }

    private fun initView() {
        binding.tvTopTitle.text = if (dataBean.checkNotNull()) "编辑下酒菜" else "发布下酒菜"
        EditInputUtils.numEditText(binding.etDesc, binding.tvWordNum, 300)
    }

    lateinit var wineryCoverBean: WineryCoverBean
    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_fragment_agency_image -> {
                if (TextUtils.isEmpty(viewModel.privateMealImgPath.value)) {
                    //添加图片/视频
                    addImgVideo()
                }else{
                    //预览
                    seeBigImg()
                }
            }
            R.id.iv_del -> {
                //删除图片
                PopUtils.showOkCancelDialog(this, "确认删除", object : PopUtils.ICallBack {
                    override fun clickOk() {
                        binding.ivFragmentAgencyImage.load(
                            ContextUtils.getCurApplication().applicationContext,
                                R.drawable.ic_upload_temp_4
                        )
                        binding.ivDel.visibility = View.GONE
                        binding.imgVideoTag.visibility = View.GONE
                        viewModel.privateMealImgPath.value=""
                        "删除成功".toast()
                    }

                    override fun clickCancel() {

                    }

                }, false, "确认", "取消")

            }
            R.id.tv_enter -> {
                if (!DoubleClickHelper.isOnDoubleClick()) {
                    //发布
                    publishOption()
                }
            }
        }
    }

    private fun seeBigImg() {
        //查看大图
        val name = binding.etName.text.toString()
        val desc = binding.etDesc.text.toString()
        val bundle = Bundle()
        bundle.putStringArrayList(Constants.KEY_URLS , arrayListOf(viewModel.privateMealImgPath.value))
        bundle.putInt(Constants.KEY_INDEX , 0)
        bundle.putStringArrayList(Constants.KEY_COMMENT_CONTENT , arrayListOf(desc))
        bundle.putStringArrayList(Constants.KEY_COMMENT_TITLE , arrayListOf(name))
        ActivityRouter.startActivity(ActivityRouter.WINE_CELLAR.IMG_VIDEO_DETAIL , bundle)
    }

    //添加图片 视频
    private fun addImgVideo() {
        WineryAboutUtils.uploadImgVideo(this, true, 0, 1)
    }

    //发布
    private fun publishOption() {
        if (TextUtils.isEmpty(viewModel.privateMealImgPath.value)) {
            "图片/视频不能为空".toast()
            return
        }
        val appetizerName = binding.etName.text.toString()
        if (TextUtils.isEmpty(appetizerName)) {
            "下酒菜名称不能为空".toast()
            return
        }
        showLoading()
        if (dataBean.checkNotNull()) {//【编辑】
            if (wineryCoverBean.type == 0) {//图片
                if (wineryCoverBean.coverUrl.startsWith("http")) {
                    viewModel.privateMealImgPath.value = wineryCoverBean.coverUrl
                    publishCommit(true, true, wineryCoverBean.coverUrl, "")
                } else {
                    //上传图片
                    uploadImagesHandler(true)
                }
            } else {
                //视频url
                if (wineryCoverBean.videoUrl.startsWith("http")) {
                    viewModel.privateMealImgPath.value = wineryCoverBean.videoUrl
                    publishCommit(true, false, wineryCoverBean.videoUrl, wineryCoverBean.coverUrl)
                } else {
                    //上传视频
                    uploadVideoHandler(true)
                }
            }
        } else {//【新增】
            if (wineryCoverBean.type == 0) {
                //上传图片
                uploadImagesHandler(false)
            } else {
                //上传视频
                uploadVideoHandler(false)
            }
        }
    }

    private fun uploadImagesHandler(isEdit: Boolean) {
        UploadMediaUtils.uploadImages(
            arrayListOf(wineryCoverBean.coverUrl),
            object : UploadMediaUtils.UploadImageListener {
                override fun onComplete(questionRespT: MultiImageResp) {
                    if (questionRespT.getData().size > 0) {
                        val coverUrl = questionRespT.getData()[0].ok
                        viewModel.privateMealImgPath.value = coverUrl
                        publishCommit(isEdit, true, coverUrl, "")
                    }
                }
            })
    }

    private fun uploadVideoHandler(isEdit: Boolean) {
        UploadMediaUtils.uploadVideo(
            wineryCoverBean.videoUrl,
            object : UploadMediaUtils.UploadVideoListener {
                override fun onProgress(uploadBytes: Long, totalBytes: Long) {
                }

                override fun onComplete(videoUrl: String?, videoCoverUrl: String) {
                    if (videoUrl.checkNotNull()) {
                        viewModel.privateMealImgPath.value = videoUrl
                        publishCommit(isEdit, false, videoUrl, videoCoverUrl)
                    }
                }
            })
    }

    private fun publishCommit(
        isEdit: Boolean,
        isImg: Boolean,
        url: String?,
        videoCoverUrl: String?
    ) {
        val appetizerDesc = binding.etDesc.text.toString()
        val appetizerName = binding.etName.text.toString()
        val sort = if (binding.etSort.text.toString().checkValue()
                .checkNotNull()
        ) binding.etSort.text.toString().checkValue() else "0"
        if (isEdit) {
            //编辑
            val id = dataBean?.id
            viewModel.reqEditPrivateMeal(
                id!!,
                appetizerDesc,
                CommonUtil.beanToJson(
                    WineryCoverBean(
                        if (isImg) url.checkValue() else videoCoverUrl.checkValue(),
                        if (isImg) "" else url.checkValue(),
                        if (isImg) 0 else 1
                    )
                ),
                appetizerName,
                sort.toInt()
            )
        } else {
            //发布
            viewModel.reqAddPrivateMeal(
                appetizerDesc,
                CommonUtil.beanToJson(
                    WineryCoverBean(
                        if (isImg) url.checkValue() else videoCoverUrl.checkValue(),
                        if (isImg) "" else url.checkValue(),
                        if (isImg) 0 else 1
                    )
                ),
                appetizerName,
                sort.toInt()
            )
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(messageBus: MessageBus) {
        var mMediaPathList = mutableListOf<WineryCoverBean>()
        if (messageBus.codeType == MessageBus.msgId_select_img_video_path_list) {
            if (messageBus.param1 is String) {//视频
                FileUtils.copyVideoFile(messageBus.param1.toString(),object:FileUtils.OnCopyFileListener{
                    override fun onCopyOver(filePath: String?) {
                        mMediaPathList.add(WineryCoverBean("", filePath.checkValue(), 1))
                    }

                    override fun onCopyError() {
                    }

                })
            } else if (messageBus.param1 is List<*>) {//图片
                var list = messageBus.param1 as List<String>
                for (imageItem in list) {
                    mMediaPathList.add(WineryCoverBean(imageItem, "", 0))
                }
            }
            wineryCoverBean = mMediaPathList[0]
            binding.ivDel.visibility = View.VISIBLE
            viewModel.privateMealImgPath.value =
                if (wineryCoverBean.type == 0) wineryCoverBean.coverUrl.checkValue() else wineryCoverBean.videoUrl.checkValue()
            binding.ivFragmentAgencyImage.load(
                ContextUtils.getCurApplication().applicationContext,
                viewModel.privateMealImgPath.value.checkValue()
            )
            binding.imgVideoTag.visibility =
                if (wineryCoverBean.type == 1) View.VISIBLE else View.GONE
        }
    }

    override fun onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        super.onDestroy()
    }
}